<!-- 商家管理页面 -->
<template>
  <PageContainer title="商家管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="searchForm.keyword" placeholder="请输入商家名称/联系人搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.region" placeholder="请选择所属地区" class="region-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="北京" value="北京"></el-option>
            <el-option label="上海" value="上海"></el-option>
            <el-option label="广州" value="广州"></el-option>
            <el-option label="深圳" value="深圳"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" class="operate-buttons">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加商家
          </el-button>
          <el-button type="danger" @click="handleBatchAudit('reject')" :disabled="selectedIds.length === 0">
            <i class="el-icon-close"></i> 批量驳回
          </el-button>
          <el-button type="success" @click="handleBatchAudit('pass')" :disabled="selectedIds.length === 0">
            <i class="el-icon-check"></i> 批量通过
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 商家表格 -->
    <el-table :data="merchantList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="商家ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="商家名称" prop="merchantName" width="200"></el-table-column>
      <el-table-column label="联系人" prop="contactPerson" width="120" align="center"></el-table-column>
      <el-table-column label="联系电话" prop="phone" width="130" align="center"></el-table-column>
      <el-table-column label="所属地区" prop="region" width="120" align="center"></el-table-column>
      <el-table-column label="营业执照" width="120" align="center">
        <template #default="scope">
          <el-image :src="scope.row.businessLicense" style="width: 40px; height: 40px; cursor: pointer;" fit="cover"
            @click="handlePreviewLicense(scope.row.businessLicense)"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.auditStatus)">
            {{ getStatusLabel(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账号状态" width="120" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" align="center"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetail(scope.row)">详情</el-button>
          <el-button type="text" v-if="scope.row.auditStatus === 'pending'"
            @click="handleAudit(scope.row, 'pass')">通过</el-button>
          <el-button type="text" v-if="scope.row.auditStatus === 'pending'" style="color: red;"
            @click="handleAudit(scope.row, 'reject')">驳回</el-button>
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 营业执照预览弹窗 -->
    <el-dialog title="营业执照预览" :visible.sync="licensePreviewVisible" width="600px">
      <el-image :src="previewLicenseUrl" style="width: 100%;" fit="contain"></el-image>
    </el-dialog>

    <!-- 添加/编辑商家弹窗 -->
    <el-dialog :title="isEdit ? '编辑商家' : '添加商家'" :visible.sync="dialogVisible" width="600px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="商家名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商家名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="所属地区" prop="region">
          <el-select v-model="form.region" placeholder="请选择所属地区">
            <el-option label="北京" value="北京"></el-option>
            <el-option label="上海" value="上海"></el-option>
            <el-option label="广州" value="广州"></el-option>
            <el-option label="深圳" value="深圳"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleLicenseUpload"
            :before-upload="handleBeforeUpload" :file-list="licenseFileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商家简介" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="5" placeholder="请输入商家简介"></el-input>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus" v-if="isEdit">
          <el-select v-model="form.auditStatus" placeholder="请选择审核状态">
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已通过" value="pass"></el-option>
            <el-option label="已驳回" value="reject"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用"
            inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getMerchantList, addMerchant, editMerchant, updateMerchantStatus, auditMerchant, batchAuditMerchant } from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  region: ''
})

// 表格数据
const merchantList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)
const selectedIds = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const licensePreviewVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const licenseFileList = ref([])
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'
const previewLicenseUrl = ref('')

// 表单数据
const form = reactive({
  id: '',
  merchantName: '',
  contactPerson: '',
  phone: '',
  email: '',
  region: '',
  address: '',
  businessLicense: '',
  description: '',
  auditStatus: 'pending', // pending-待审核, pass-已通过, reject-已驳回
  status: 1
})

// 表单校验规则
const formRules = reactive({
  merchantName: [
    { required: true, message: '请输入商家名称', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所属地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ]
})

// 审核状态标签类型
const getStatusTagType = (status) => {
  const statusTypeMap = {
    pending: 'warning',
    pass: 'success',
    reject: 'danger'
  }
  return statusTypeMap[status] || 'default'
}

// 审核状态文本
const getStatusLabel = (status) => {
  const statusLabelMap = {
    pending: '待审核',
    pass: '已通过',
    reject: '已驳回'
  }
  return statusLabelMap[status] || '未知状态'
}

// 获取商家列表
const fetchMerchantList = async () => {
  try {
    loading.value = true
    const res = await getMerchantList({
      keyword: searchForm.keyword,
      region: searchForm.region,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    merchantList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取商家列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchMerchantList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchMerchantList()
}

// 选择改变（批量操作）
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}

// 添加商家
const handleAdd = () => {
  isEdit.value = false
  // 重置表单
  form.id = ''
  form.merchantName = ''
  form.contactPerson = ''
  form.phone = ''
  form.email = ''
  form.region = ''
  form.address = ''
  form.businessLicense = ''
  form.description = ''
  form.auditStatus = 'pending'
  form.status = 1
  licenseFileList.value = []
  dialogVisible.value = true
}

// 编辑商家
const handleEdit = (row) => {
  isEdit.value = true
  // 填充表单
  form.id = row.id
  form.merchantName = row.merchantName
  form.contactPerson = row.contactPerson
  form.phone = row.phone
  form.email = row.email
  form.region = row.region
  form.address = row.address
  form.businessLicense = row.businessLicense
  form.description = row.description
  form.auditStatus = row.auditStatus
  form.status = row.status
  // 图片列表
  licenseFileList.value = row.businessLicense ? [{ url: row.businessLicense }] : []
  dialogVisible.value = true
}

// 查看商家详情
const handleViewDetail = (row) => {
  console.log('商家详情:', row)
  ElMessage.info('查看商家详情功能')
  // 实际项目中可打开详情弹窗或跳转详情页
}

// 预览营业执照
const handlePreviewLicense = (url) => {
  previewLicenseUrl.value = url
  licensePreviewVisible.value = true
}

// 审核商家
const handleAudit = async (row, auditResult) => {
  try {
    await auditMerchant({
      id: row.id,
      auditStatus: auditResult
    })
    ElMessage.success(`审核${auditResult === 'pass' ? '通过' : '驳回'}成功`)
    fetchMerchantList()
  } catch (error) {
    ElMessage.error(`审核${auditResult === 'pass' ? '通过' : '驳回'}失败`)
  }
}

// 批量审核
const handleBatchAudit = async (auditResult) => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要审核的商家')
    return
  }

  try {
    await batchAuditMerchant({
      ids: selectedIds.value,
      auditStatus: auditResult
    })
    ElMessage.success(`批量${auditResult === 'pass' ? '通过' : '驳回'}成功`)
    selectedIds.value = []
    fetchMerchantList()
  } catch (error) {
    ElMessage.error(`批量${auditResult === 'pass' ? '通过' : '驳回'}失败`)
  }
}

// 改变商家状态
const handleStatusChange = async (row) => {
  try {
    await updateMerchantStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success(`商家已${row.status === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    // 失败时回滚状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑商家
      await editMerchant(form)
      ElMessage.success('编辑商家成功')
    } else {
      // 添加商家
      await addMerchant(form)
      ElMessage.success('添加商家成功')
    }
    dialogVisible.value = false
    fetchMerchantList()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑商家失败' : '添加商家失败')
  }
}

// 营业执照上传成功
const handleLicenseUpload = (response) => {
  form.businessLicense = response.data.url
  licenseFileList.value = [{ url: response.data.url }]
}

// 上传前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value?.resetFields()
  licenseFileList.value = []
  dialogVisible.value = false
  licensePreviewVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchMerchantList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;

  .search-input {
    width: 100%;
  }

  .region-select {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>